<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CustomerRequest;
use Illuminate\Http\Request;
use App\Models\CustomerChargeModel;
use App\Models\CustomerInvoiceModel;
use App\Models\CustomerModel;
use App\Models\CustomerTypeModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class Customer extends Controller
{

//===========客户==============
    use CustomerRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('customer', '');
        $is_update = $request->input('isUpdate', 0);
        $customer_type_id = $request->input('customerType', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $query = CustomerModel::query()
            ->with('create_admin')->with('customer_type')->with('charges');
//            ->where('is_big', 0);

        if($name) {
            $query->where(function($query) use ($name){
                $query->where('name', 'like', "%$name%")
                    ->orWhere('sn', 'like', "%$name%");
            });
        }

        if($customer_type_id) {
            $query->where('customer_type_id', $customer_type_id);
        }

        if($create_start && $create_end){
            $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'sn' => $item->sn,
                'name' => $item->name,
                'review_status' => $item->review_status,
                'customer_type_id' => $item->customer_type_id,
                'customer_type_name' => $item->customer_type ? $item->customer_type->name : '',
                'account' => $item->account,
                'account_status' => $item->account_status,
                'account_status_name' => CustomerModel::ACCOUNT_STATUS[$item->account_status] ?? '',
                'created_at' => $item->created_at->toDateTimeString(),
                'handle_staff_id' => $item->handle_staff_id,
                'handle_staff_name' => $item->handle_staff?->name ?? '',
                'remark' => $item->remark,
                'charge_currency' => $item->charge_currency,
                'charges' => $item->charges,
                'invoice' => $item->invoice,
                'contact_person' => $item->contact_person,
                'contact_phone' => $item->contact_phone,
                'email' => $item->email,
                'wechat' => $item->wechat,
                'province_id' => $item->province_id,
                'city_id' => $item->city_id,
                'addr' => $item->addr,
                'contract' => $item->contract,
                // 'remark' => $item->remark,
                // 'handle_staff_id' => $item->handle_staff_id,
                'is_delay' => $item->is_delay,
                // 'contract' => $item->contract,
                'contract_effect_date' => $item->contract_effect_date,
                'validity_period' => $item->validity_period,
                'settle_type' => $item->settle_type,
                'collect_bill_fee' => $item->collect_bill_fee,
                'collect_sub_bill_fee' => $item->collect_sub_bill_fee,
                'ticket' => [
                    'invoice_title' => $item->invoice?->invoice_title ?? '',
                    'tax_number' => $item->invoice?->tax_number ?? '',
                    'bank_name' => $item->invoice?->bank_name ?? '',
                    'bank_account' => $item->invoice?->bank_account ?? '',
                    'address' => $item->invoice?->address ?? '',
                    'phone' => $item->invoice?->phone ?? '',
                ],
                'sort_name' => $item->sort_name,
                'name_en' => $item->name_en,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    //添加客户
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        if(!empty($params['customer_type_id'])) {
            $customer_type = CustomerTypeModel::find($params['customer_type_id']);
            if(!$customer_type){
                return $this->error('客户类型不存在');
            }
        }

        if(!empty($params['account'])){
            $account = CustomerModel::where('account', $params['account'])->first();
            if($account){
                return $this->error('客户账号已存在');
            }
        }

        $find_name_en = CustomerModel::where('name_en', $params['name_en'])->first();
        if($find_name_en){
            return $this->error('客户英文名已存在');
        }

        $customer = new CustomerModel();
        $customer->name = $params['name'];
        $customer->sort_name = $params['sort_name'] ?? '';
        $customer->name_en = $params['name_en'] ?? '';
        $customer->customer_type_id = $params['customer_type_id'] ?? 0;
        $customer->email = $params['email'];
        $customer->contact_person = $params['contact_person'];
        $customer->contact_phone = $params['contact_phone'];
        $customer->account = $params['account'];
        $customer->contract = $params['contract'];
        $customer->collect_bill_fee = $params['collect_bill_fee'] ?? CustomerModel::COLLECT_BILL_FEE;
        $customer->collect_sub_bill_fee = $params['collect_sub_bill_fee'] ?? CustomerModel::COLLECT_SUB_BILL_FEE;
        $customer->settle_type = $params['settle_type'] ?? CustomerModel::TICK_SETTLE;
        $customer->validity_period = $params['validity_period'] ?? 1;
        $customer->contract_effect_date = $params['contract_effect_date'] ?? null;
        $customer->is_delay = $params['is_delay'] ?? CustomerModel::CONTRACT_DELAY;
        $customer->handle_staff_id = $params['handle_staff_id'] ?? 0;
        $customer->remark = $params['remark'] ?? '';
        $customer->wechat = $params['wechat'] ?? '';
        $customer->province_id = $params['province_id'] ?? 0;
        $customer->city_id = $params['city_id'] ?? 0;
        $customer->district_id = $params['district_id'] ?? 0;
        $customer->addr = $params['addr'] ?? '';
        $customer->created_admin_id = $auth->id;
        $customer->account_status = CustomerModel::NORMAL_ACCOUNT;
        $customer->review_status = 2; //自动审核通过
        $customer->password = password_hash('EML123465', PASSWORD_DEFAULT);
        $customer->save();
        $customer->sn = 'EML' . $customer->id;
        $customer->save();

        return $this->success();
    }

    public function update(Request $request, int $id){
        $params = $request->all();
        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $customer = CustomerModel::find($id);

        if(!empty($params['customer_type_id'])) {
            $customer_type = CustomerTypeModel::find($params['customer_type_id']);
            if(!$customer_type){
                return $this->error('客户类型不存在');
            }
        }

//        $find_name_en = CustomerModel::where('name_en', $params['name_en'])->first();
//        if($find_name_en){
//            return $this->error('客户英文名已存在');
//        }

        $customer->name = $params['name'];
        $customer->sort_name = $params['sort_name'] ?? '';
        $customer->name_en = $params['name_en'] ?? '';
        $customer->customer_type_id = $params['customer_type_id'] ?? 0;
        $customer->email = $params['email'];
        $customer->contact_person = $params['contact_person'];
        $customer->contact_phone = $params['contact_phone'];
        $customer->account = $params['account'];
        $customer->contract = $params['contract'];
        $customer->collect_bill_fee = $params['collect_bill_fee'] ?? CustomerModel::COLLECT_BILL_FEE;
        $customer->collect_sub_bill_fee = $params['collect_sub_bill_fee'] ?? CustomerModel::COLLECT_SUB_BILL_FEE;
        $customer->settle_type = $params['settle_type'] ?? CustomerModel::TICK_SETTLE;
        $customer->validity_period = $params['validity_period'] ?? 1;
        $customer->contract_effect_date = $params['contract_effect_date'] ?? null;
        $customer->is_delay = $params['is_delay'] ?? CustomerModel::CONTRACT_DELAY;
        $customer->handle_staff_id = $params['handle_staff_id'] ?? 0;
        $customer->remark = $params['remark'] ?? '';
        $customer->wechat = $params['wechat'] ?? '';
        $customer->province_id = $params['province_id'] ?? 0;
        $customer->city_id = $params['city_id'] ?? 0;
        $customer->district_id = $params['district_id'] ?? 0;
        $customer->addr = $params['addr'] ?? '';
        $customer->save();

        return $this->success();
    }

    public function delete(int $id){
        $customer = CustomerModel::find($id);
        if(!$customer){
            return $this->error('记录不存在');
        }
        $customer->delete();
        return $this->success();
    }

    //设置账号
    public function set_account(Request $request, $id){
        $params = $request->all();
        $validator = Validator::make($params, [
            'account_status' => 'required|in:1,2'
        ], [
            'account_status.required' => '请选择账号状态',
            'account_status.in' => '账号状态错误'
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $customer = CustomerModel::find($id);
        if(!$customer){
            return $this->error('记录不存在');
        }

        $customer->account_status = $params['account_status'];
        $customer->save();

        return $this->success();
        
    }

    //收费设置
    public function set_charge(Request $request, $id) {
        $params = $request->all();
        $validator = Validator::make($params, [
            'charge_currency' => 'required',
            'charges' => 'array',
        ], [
            'charge_currency.required' => '请选择收费币种',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $pre_end = -INF;
        if(is_array($params['charges']) && !empty($params['charges'])){
            foreach($params['charges'] as $charge){

                $validator = Validator::make($charge, [
                    'start' => 'required|numeric|min:0',
                    'end' => 'required|numeric',
                    'price' => 'required|numeric|min:0',
                ], [
                    'start.required' => '请设置区间开始重量',
                    'start.numeric' => '区间开始重量必须为数字',
                    'start.min' => '区间开始重量必须大于0',
                    'end.required' => '请设置区间结束重量',
                    'end.numeric' => '区间结束重量必须为数字',
                    'price.required' => '请设置区间价格',
                    'price.numeric' => '区间价格必须为数字',
                    'price.min' => '区间价格必须大于0',
                ]);
        
                if ($validator->fails()) {
                    $err = $validator->errors()->first();
                    return $this->error($err);
                }

                if($charge['end'] <= $charge['start']){
                    return $this->error('重量区间错误');
                }
                
                if($charge['start'] <= $pre_end){
                    return $this->error('收费区间设置错误');
                }

                $pre_end = $charge['end'];
            }
        }
            

        $customer = CustomerModel::find($id);
        if(!$customer){
            return $this->error('记录不存在');
        }

        DB::beginTransaction();
        try {
            $customer->charge_currency = $params['charge_currency'];
            $customer->save();

            $charge_inserts = [];
            foreach($params['charges'] as $charge){
                $charge_inserts[] = [
                    'customer_id' => $id,
                    'start' => $charge['start'],
                    'end' => $charge['end'],
                    'price' => $charge['price'],
                ];
            }

            CustomerChargeModel::where('customer_id', $id)->delete();
            CustomerChargeModel::insert($charge_inserts);
           
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        
        return $this->success();
    }

    //开票设置
    public function set_invoice(Request $request, $id) {
        $params = $request->all();

        $validator = Validator::make($request->all(), [
            'invoice_title' => 'required|string|max:255',
            'tax_number' => 'required|string|max:255',
            'bank_name' => 'required|string|max:255',
            'bank_account' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'phone' => 'required|string|max:255',
        ], [
            'invoice_title.required' => '请填写发票抬头',
            'invoice_title.max' => '发票抬头长度不能超过255个字符',
            'tax_number.required' => '请填写公司税号',
            'tax_number.max' => '公司税号长度不能超过255个字符',
            'bank_name.required' => '请填写开户行',
            'bank_name.max' => '开户行长度不能超过255个字符',
            'bank_account.required' => '请填写开户银行账号',
            'bank_account.max' => '开户银行账号长度不能超过255个字符',
            'address.required' => '请填写公司地址',
            'address.max' => '公司地址长度不能超过255个字符',
            'phone.required' => '请填写公司电话',
            'phone.max' => '公司电话长度不能超过255个字符',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $customer = CustomerModel::find($id);
        if (!$customer) {
            return $this->error('客户未找到');
        }

        $invoice = $customer->invoice;
        if(!$invoice) {
            $invoice = new CustomerInvoiceModel();
            $invoice->customer_id = $id;
        }else{
            $invoice->is_update = 1;
        }

        $invoice->invoice_title = $params['invoice_title'];
        $invoice->tax_number = $params['tax_number'];
        $invoice->bank_name = $params['bank_name'];
        $invoice->bank_account = $params['bank_account'];
        $invoice->address = $params['address'];
        $invoice->phone = $params['phone'];

        $invoice->save();

        return $this->success();

    }

//===========客户==============


//===========客户类型===============
    //客户类型列表
    public function types(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $query = CustomerTypeModel::query()->with('create_admin')->withCount('customers');

        if($name){
            $query = $query->where('name', 'like', '%'.$name.'%');
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'customers_count' => $item->customers_count,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin->staff->name ?? ''
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    //添加客户类型
    public function type_add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();
        $validator = Validator::make($params, [
            'name' => 'required|max:255'
        ], [
            'name.required' => '请填写类型名称'
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $customer_type = new CustomerTypeModel();
        $customer_type->name = $params['name'];
        $customer_type->created_admin_id = $auth->id;
        $customer_type->save();

        return $this->success();
    }

    //更行客户类型
    public function type_update(Request $request, int $id){
        $params = $request->all();
        $validator = Validator::make($params, [
            'name' => 'required|max:255'
        ], [
            'name.required' => '请填写类型名称'
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $customer_type = CustomerTypeModel::find($id);
        if (!$customer_type) {
            return $this->error('记录不存在');
        }
        $customer_type->name = $params['name'];
        $customer_type->save();

        return $this->success();
    }

    //删除客户类型
    public function type_del(int $id){
        $type = CustomerTypeModel::query()->withCount('customers')->find($id);

        if(!$type) {
            return $this->error('记录不存在');
        }

        if($type->customers_count > 0) {
            return $this->error('该类型下有客户，无法删除');
        }

        $type->delete();
        return $this->success();
    }

//===========客户类型===============
    
    //待审核列表
    public function review_list(Request $request){
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $query = CustomerModel::query()
            ->whereIn('review_status', [1,3]) //待审核
            ->with('create_admin')
            ->with('customer_type')
            ->with('charges')
            ->with('invoice');

        if($name){
            $query = $query->where('name', 'like', '%'.$name.'%');
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'contact_person' => $item->contact_person,
                'contact_phone' => $item->contact_phone,
                'wechat' => $item->wechat,
                'contract' => $item->contract,
                'review_status' => $item->review_status,
                'created_at' => $item->created_at->toDateTimeString(),
                'remark' => $item->remark,
                'handle_staff_name' => $item->handle_staff->name ?? '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);

    }

    //同意开户
    public function pass(Request $request) {
        $id = $request->input('id');
        $remark = $request->input('remark', '');
        $settle_type = $request->input('settle_type', CustomerModel::TICK_SETTLE);
        $customer_type_id = $request->input('customer_type_id', 0);

        $customer = CustomerModel::find($id);
        if(!$customer) {
            return $this->error('记录不存在');
        }

        if($customer->review_status != 1)  {
            return $this->error('该记录不是待审核状态');
        }

        $customer->review_remark = $remark;
        $customer->settle_type = $settle_type;
        $customer->customer_type_id = $customer_type_id;
        $customer->review_status = 2;
        $customer->save();
        return $this->success();
    }

    //拒绝开户
    public function reject(Request $request) {
        $id = $request->input('id');
        $remark = $request->input('remark', '');

        $customer = CustomerModel::find($id);
        if(!$customer) {
            return $this->error('记录不存在');
        }

        if($customer->review_status != 1)  {
            return $this->error('该记录不是待审核状态');
        }

        $customer->review_remark = $remark;
        $customer->review_status = 3;
        $customer->save();
        return $this->success();
    }

    public function big_list()
    {
        $customer = CustomerModel::query()
            ->with('customer_type')
            ->with('resource')
            ->where('customer_type_id', 16)
            ->get();

        $list = $customer->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'sn' => $item->sn,
                'customer_type_name' => $item->customer_type->name ?? '',
                'resource_code' => $item->resource->code ?? '',
            ];
            return $res;
        });
        return $this->success($list);
    }

    /**
     * Notes:大客户下拉
     * User: xiangzi
     * Date: 2024/10/26
     * Time: 下午5:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function platform_select() {
        $customer = CustomerModel::query()
            ->select(['id', 'name'])
            ->where('is_big', 1)
            ->get()
            ->toArray();
        return $this->success($customer);
    }


}
